<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>扇形</title>
		<style type="text/css">
			*{
				padding: 0;
				margin: 0;
			}
			
			.container {
				width: 100vw;
				height: 100vh;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			
			canvas {
				width: 500px;
				height: 500px;
				border: 2px solid blue;
			}
		</style>
	</head>
	<body>
		<div id="answer"></div>
		<div class="container">
			<canvas id="canvas" width="500" height="500"></canvas>
		</div>
	</body>
	<script type="text/javascript">
		window.onload = function() {
			let oCanvas = document.getElementById('canvas');
			
			console.dir(oCanvas);
			
			let oPen = oCanvas.getContext("2d");
			
			console.dir(oPen);

			let data = [{
				name: '第一季度',
				value: 140,
				color: 'red'
			}, {
				name: '第二季度',
				value: 100,
				color: 'purple'
			}, {
				name: '第三季度',
				value: 170,
				color: 'paleturquoise'
			}, {
				name: '第四季度',
				value: 130,
				color: 'blue'
			}];

			//oPen 笔的对象  x 圆心坐标  y 圆心坐标  r 半径  data 数据源
			createSector(oPen, 250, 250, 150, data);
			createName(oPen, 350, 30, data);

			function createSector(oPen, x, y, r, data) {
				let sum = 0;
				for(var i = 0; i < data.length; i++) {
					sum += data[i].value;
				}
				for(var i = 0; i < data.length; i++) {
					data[i].percentage = ((data[i].value * 1.0) / sum) * 360;
				}

				let starAngle = 0;

				for(var i = 0; i < data.length; i++) {
					oPen.beginPath();
					oPen.moveTo( x, y);
					oPen.arc(x, y, r, starAngle, starAngle + (Math.PI / 180) * data[i].percentage, false);
					starAngle += (Math.PI / 180) * data[i].percentage;
					oPen.fillStyle = data[i].color;
					oPen.fill();
				}
			}
			function createName(oPen, x, y, data) {
					oPen.font='bold  20px 微软雅黑';
					for(var i=0;
					i<data.length;
					i++) {
						name=data[i].name+'  '+data[i].value;
						oPen.fillStyle=data[i].color;
						oPen.fillText(name, x, y);
						y+=30;
					}
				}
		}
	</script>
	</body>

</html>